<!--组件-API合约-->
<template>
  <div class="api">
    <template  v-if="api">
      <div class="row acenter" @click="apiClick">
        <LImage class="api-image" :src="Config.img('v2_' +api.exchangeName.toLowerCase()+'.png')"></LImage>

        <text class="font28 text1">{{api.apiName+'('+T('合约')+')'}}</text>
        <text class="font20 text2" v-if="api.remarks && api.remarks.length">{{'(' + api.remarks + ')'}}</text>
        <LImage class="arrow" :src="Config.img('xiala.png')"></LImage>
      </div>

      <div class="row acenter" v-if="!trust" @click="explainClick">
        <text class="font28 text3">{{T('全仓策略')}}</text>
        <LImage class="edit" :src="Config.img('wenhao.png')"></LImage>
      </div>
    </template>
  </div>
</template>

<script>

import math from "@/_js/math";

//功能
import navigator from "@/_js/navigator"; 
import broadcast from "@/_js/broadcast"; 
import modal from "@/_js/modal";
import Config from "@/_js/config";
import API from "@/_js/api";

const weexFunction = weex.requireModule("WeexFunction");
const globalEvent = weex.requireModule('globalEvent');

import I18N from "@/_i18n/i18n";
var T = I18N.t;

export default {

  model:{
    prop:"api",
    event:"change",
  },

  props:{

    api:{
      type:Object,
      default:undefined,
    },

    copyPair: {  //复制配置-交易对
      type:Object,
      default:undefined,
    },

    exchanges:{
      type:Object,
      default: API.getCExchanges(),
    },

    trust:{ //turn 托管界面使用
      type:Boolean,
      default:false,
    },
  },

  data() {
    return {
      T:T,
      Config:Config,
      math:math,
      apiTag:'UP_DEFAULT_API_USDT', //USDT合约API-默认配置标识
    };
  },

  mounted(){
    this.initApiCopy();
    
    //Api更新通知
    globalEvent.addEventListener("apiUp",(e)=>{
      if (this.api.apiId == '') {
        API.getApis('YES', 'USDT', this.exchanges, (apis)=>{
          if (this.api.apiId == '' && apis.length) {
            this.initApiCopy();
          }
        });
      } else {

        API.getApi(this.api.apiId, 'all', (api)=>{
          this.$emit("change", api);
          this.$emit("apiMoneyChange");
        });
      }
    });
  },

  methods:{
    //初始化复制参数api
    initApiCopy() {
      if (!this.copyPair) {
        this.initApi();
        return;
      }

      var exchangeName = this.copyPair.exchangeName;
      API.getMockApi(exchangeName, (api)=>{

        API.getApis('YES', 'USDT', [exchangeName], (apis)=>{

        api = {'exchangeName':api.exchangeName,
                'exchangeId':api.exchangeId,
                'apiName':'Binance',
                'apiId':''};
          for (let index = 0; index < apis.length; index++) {
            var data = apis[index];
            if (!data.isFundApi) {
              api = data;
              break;
            }
          }

          this.apiChange(api, this.copyPair.counterCoin, this.copyPair.baseCoin);
        });
      });
    },

    //初始化API
    initApi() {
      
      var exchange = this.exchanges[0];
      API.getMockApi(exchange, (api)=>{

        API.getApis('YES', 'USDT', this.exchanges, (apis)=>{

          weexFunction.getConfig(this.apiTag,(e)=>{
            
            var counterCoin = 'BTC';
            var baseCoin = 'USDT';
            api = {'exchangeName':api.exchangeName,
                   'exchangeId':api.exchangeId,
                   'apiName':'Binance',
                   'apiId':''};
            for (let index = 0; index < apis.length; index++) {
              var data = apis[index];
              if (!data.isFundApi) {
                api = apis[index];
                break;
              }
            }

            var config = e.length ? JSON.parse(e) : null;
            if (config) {
              for (let index = 0; index < apis.length; index++) {
                var apix = apis[index];
                if (apix.apiId == config.apiId) {
                  api = apix;
                  counterCoin = config.counterCoin ? config.counterCoin : counterCoin;
                  baseCoin = config.baseCoin ? config.baseCoin : baseCoin;
                  this.apiChange(api, counterCoin, baseCoin);
                  return;
                }
              }
            }

            this.apiChange(api, counterCoin, baseCoin);
          });
        });
      });
    },

    //设置默认Api
    setDefaultApi(apiId, counterCoin, baseCoin) {
      if(apiId.length == 0) {
        return;
      }
      /*设置配置*/
      var setConfig = (apiId, counterCoin, baseCoin)=>{
        var dict = {'apiId':apiId,
                  'counterCoin':counterCoin, 
                  'baseCoin':baseCoin};
        var str = JSON.stringify(dict);
        weexFunction.setConfig(this.apiTag, str,()=>{});
      }
      
      if (counterCoin && baseCoin) {
        
        setConfig(apiId, counterCoin, baseCoin);
      } else {

        weexFunction.getConfig(this.apiTag,(e)=>{
          var config = e.length ? JSON.parse(e) : null;
          if (config) {
            setConfig(apiId, config.counterCoin, config.baseCoin);
          }
        });
      }
    },

    /********************************** 通信方法*/
    //APi改变
    apiChange(api, counterCoin, baseCoin){

      this.setDefaultApi(api.apiId, counterCoin, baseCoin);
      
      this.$emit("change", api);
      this.$emit("apiChange", counterCoin, baseCoin);
    },

    /********************************** 点击触发*/
    //API
    apiClick(){
      
      var param =  {'apiId':this.api.apiId, 'exchange':this.exchanges};
      navigator.openDialog('upContract/CSelectApi', param);

      broadcast.subscribeOnce('CSelectApi', (data)=>{
        this.apiChange(data);
      });
    },

    //全仓阈值
    explainClick() {
      modal.alert(T('全仓策略是指，单币种合约将被设置为全仓模式，但不与其他币种共用担保资产（各交易所定义的全仓或逐仓模式有所不同），此币种资产将全部被策略占用，剩余未投入资产将自动转出至币币或资金账户（实际价值低于1USDT的资产可能不会被转出）'),()=>{
      });
    },
  }
}
</script>


<style src="@/_css/style.css"></style>
<style scoped>
.api{
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.api-image{
  width: 48px;
  height: 48px;
  margin-right: 20px;
}
.edit{
  width: 32px;
  height: 32px;
  margin-left: 16px;
}
.arrow{
  width: 20px;
  height: 20px;
  margin-left: 20px;
  margin-right: 20px;
}
</style>
